using IGeekFan.AspNetCore.Knife4jUI;
using Microsoft.EntityFrameworkCore;
using NLog.Web;
using RBAC.Interstructrue;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api;
using System.Reflection;
using Yitter.IdGenerator;
using Minio;
using RBAC.Write.Api.Infrastructure.Storage;
using RBAC.Write.Api.Middlewares;
using RBAC.Write.Api.Application.Interfaces;
using RBAC.Write.Api.Application.Handler;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(p =>
{
    var path = Path.Combine(AppContext.BaseDirectory, "RBAC.Write.Api.xml");
    p.IncludeXmlComments(path,true);
});

// 数据库连接工厂 (Dapper)
builder.Services.AddScoped<IDbConnectionFactory, DbConnectionFactory>();

// EF Core数据库上下文 (暂时保留)
builder.Services.AddDbContext<RBACDbContext>(x =>
{
    x.UseMySql(builder.Configuration.GetConnectionString("MySQL"), new MySqlServerVersion("5.7"));
});

//中介者
builder.Services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));
// 自动映射
builder.Services.AddAutoMapper(typeof(RBACAutoMapper));
// 日志
builder.Host.UseNLog();
// 雪花id
YitIdHelper.SetIdGenerator(new IdGeneratorOptions());
// 仓储 (同时支持EF Core和Dapper)
builder.Services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));

// 生产工单 写侧服务注册
builder.Services.AddScoped<IProductionWorkOrderWriteService, ProductionWorkOrderWriteService>();

// MinIO configuration
var minioEndpoint = builder.Configuration["Minio:Endpoint"];
var minioAccessKey = builder.Configuration["Minio:AccessKey"];
var minioSecretKey = builder.Configuration["Minio:SecretKey"];
var minioUseSSL = bool.TryParse(builder.Configuration["Minio:UseSSL"], out var u) && u;

builder.Services.AddSingleton<IMinioClient>(_ =>
{
    var mc = new MinioClient()
        .WithEndpoint(minioEndpoint)
        .WithCredentials(minioAccessKey, minioSecretKey);
    if (minioUseSSL)
    {
        mc = mc.WithSSL();
    }
    return mc.Build();
});

builder.Services.AddSingleton<IObjectStorage, MinioObjectStorage>();


var app = builder.Build();

// Configure the HTTP request pipeline.
//if (app.Environment.IsDevelopment())
//{
    app.UseSwagger();
    //app.UseSwaggerUI();
    app.UseKnife4UI();
//}
//跨域
app.UseCors(x => x.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());
// 操作日志
app.UseOperationLogging();
app.UseAuthorization();

app.MapControllers();

app.Run();
